package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @Autowired // 从容器中获取对象
    RedisTemplate redisTemplate;

    @RequestMapping("/loginPage.do")
    public String loginPage(){


        return "login";
    }

    @RequestMapping("/login.do")
    public String login(@Valid User login, BindingResult result, Model model, HttpServletResponse response){

        if (result.hasErrors()){

            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());

            return "login";
        }

       User userDB =  userMapper.selectByName(login.getName());
        if (userDB == null){
            model.addAttribute("error","用户名不存在");

            return "login";
        }

        String loginPassword = login.getPassword();

        String password = userDB.getPassword();
        String salt = userDB.getSalt();

        String md5String = Md5Utils.getMD5String(loginPassword + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");

            return "login";
        }

        // 加密用户信息 得到token， 把token放入cookie, 把cookie返回给浏览器，  设置令牌的有效期30分钟，cookie的有效期 30分钟

        TokenUtils.responseTokenByCookie(userDB,response,30);

        // 用户信息 存储到Redis里  并且设置过期时间为token的过期时间（30min）

        redisTemplate.opsForValue().set(userDB.getName(), JSON.toJSONString(userDB),30, TimeUnit.MINUTES);

        // 给用户管理员 发送短信 告知登录信息
        boolean b = ZzyUtils.sendSms("15234269854", userDB.getName() + "登录成功", 5);

        return "redirect:list.do";
    }



}
